package com.kdtech.analyse.blog;
import com.kdtech.crawler.CrawlHTML;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * 8063
 * http://blog.cntv.cn/ 央视博客
 * @author KK
 *
 */
public class CnstockBlogAnalyse implements AnalyseNews{

	
	public boolean isDetailPage(String url) {
		String[] regex = {
				"http://.*.blog.cnstock.com/archives/[0-9]+/[0-9]+.html",
				"http://.*.blog.cnstock.com/[0-9]+.html",
				};
		return RegexUtils.matchAny(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {

		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();

		String title = null;
		String content = null;
		Long date = null;
		Integer commnetNum = null;
		Integer clickNum = null;
		Integer deliverNum = null;
		String updateUrl = url;
		String author=null;
		Document doc = Jsoup.parse(htmltxt);

		title = doc.select("div.title").text();
		title = StringUtils.substringBefore(title, "作者");

		date = DateUtils.matchDate(doc.select("span.addtime").text()) ;
		if (date == null) {
			date = DateUtils.matchDate(doc.select("div.ll-time").text()) ;
		}

		content = HtmlCleaner.getContentHtml(url,  doc.select("div.logtxt"));
		if (StringUtils.isBlank(content)) {
			content = HtmlCleaner.getContentHtml(url,  doc.select("div.logtext"));
		}
		
		author = doc.select("div.ll-span").text();
//		System.err.println(doc.select("span#blogname").text());
		if (StringUtils.isBlank(author)) {
			author = doc.select("span.addtime").text();
			author = StringUtils.substringBetween(author, "作者", "日期");
		}
		String commTxt = doc.select("div[align=right]").text();
		clickNum =NumberUtils.matchNumber(StringUtils.substringBetween(commTxt, "阅读全文(", ")"));
		commnetNum =NumberUtils.matchNumber(StringUtils.substringBetween(commTxt, "回复(", ")"));
//		deliverNum = NumberUtils.matchNumber(doc.select("a:containsOwn(收藏\\()").text());

			NewsMeta news = new NewsMeta();
			news.setUrl(url);
			news.setType(7);
			news.setTitle(StringUtils.trimSpace(title));
			news.setCommentNum(commnetNum);
			news.setAuthor(author);
			news.setClickNum(clickNum);
			//news.setDeliverNum(deliverNum);
			news.setContent(StringUtils.trimSpace(content));
			news.setDate(date);
			news.setUpdateUrl(updateUrl);
			return news;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if (meta!=null &&StringUtils.isNotBlank(meta.getUpdateUrl())){
			UrlMeta urlMeta = CrawlHTML.responseToURL(meta.getUpdateUrl());
			if (urlMeta!=null && urlMeta.getHtml()!=null){
				return parserHtml(urlMeta);
			}
		}
		return null;
	}

	

	
}
